import { post, get, download } from "./request";
import { ConnectRes, DataBase, Generator, CodeFile } from "@/types/interfaces";
import { Result } from "@/types/common";

export const api = {
  isAlive: "/db/isAlive",
  dbConnect: "/db/connect",
  dbClose: "/db/close",
  dbTables: "/db/tables",
  generate: "/generate",
  getFiles: "/files",
  sseConnect: import.meta.env.VITE_BASE_API + "/sse/connect/",
  sseClose: "/sse/close",
  previewFile: "/sse/preview",
  download: "/download",
};

export const isAlive = async (): Promise<Result<any>> => {
  return await get(api.isAlive);
};

export const dbConnect = async (
  param: DataBase
): Promise<Result<ConnectRes>> => {
  return await post(api.dbConnect, param);
};

export const dbClose = async (): Promise<Result<any>> => {
  return await post(api.dbClose, null, {
    keepalive: true,
  });
};

export const dbTables = async (): Promise<Result<string[]>> => {
  return await get(api.dbTables);
};

export const generate = async (param: Generator): Promise<Result<any>> => {
  return await post(api.generate, param);
};

export const getFiles = async (): Promise<Result<CodeFile[]>> => {
  return await get(api.getFiles);
};

export const sseClose = async (): Promise<Result<any>> => {
  return await post(api.sseClose);
};

export const previewFile = async (fileIndex: number): Promise<Result<any>> => {
  return await get(api.previewFile, { fileIndex });
};

export const downloadFile = async (
  fileIndex: number[],
  filename?: string
): Promise<Result<any>> => {
  return await download(
    api.download + "?fileIndex=" + fileIndex.join(","),
    filename
  );
};
